/**
 * 播放器核心
 * Created by acgit on 2015/7/23.
 * Copyright 2015 by Ruiko Of AcGit.cc
 * @license MIT
 *
 * 版本2.0 2015/08/12
 */


;
(function ($) {
    var ManPlayer = function (element, options) {
        this.$element = $(element);
        this.options = options;
        $(element).data("paused", 1);
        var that = this;
        //播放器全局样式
        this.$element.css({
            "position": "relation",
            //"left":this.options.left,
            //"top":this.options.top,
            "width": this.options.width,
            "height": this.options.height
            //"overflow": "hidden"
        });

        //选择器规范
        this.$element.addClass("danmu-player");
        if (!$(element).attr("id"))
            $(element).attr("id", (Math.random() * 65535).toString());
        this.id = "#" + $(element).attr("id");

        //控件添加
        //this.$element.css("height", this.$element.height() + 40);
        this.$element.append('<video id="man_video" class="danmu-video" src="'+ options.src +'" width="'+ options.width +'" height="'+ options.height +'" poster="'+ options.poster +'"></video>');
        this.$element.append('<div class="danmu-player-load" ></div>');
        this.$element.append('<div class="danmu-player-ctrl" ></div>');
        this.$ctrl = $(this.id + " .danmu-player-ctrl");
        this.$ctrl.append('<div class="ctrl-progress-box">' +
            '<span class="ctrl-progress-time"></span>' +
            '<div class="ctrl-progress"><div class="current">' +
                '<span class="progress-handle"></span></div>' +
            '<div class="buffered"></div></div></div>');
        this.$ctrl.append('<div class="ctrl-main"></div>');
        this.$ctrlMain = $(this.id + " .ctrl-main");
        this.$ctrlMain.append('<div class="play-btn ctrl-btn"><span class="glyphicon glyphicon-play" aria-hidden="true"></span></div>');
        if(this.options.nextButton){
            this.$ctrlMain.append('<div class="next-btn ctrl-btn"><span class="glyphicon glyphicon-forward" aria-hidden="true"></span></div>');
        }
        this.$ctrlMain.append('<div class="time-box ctrl-btn">'+
            '<span class="current-time">0:00</span>'+
            '<span class="slash">/</span>'+
            '<span class="duration">0:00</span></div>');
        this.$ctrlMain.append('<div class="full-screen ctrl-btn-right"><span title="全屏播放" class="glyphicon glyphicon-resize-full" aria-hidden="true"></span></div>');
        this.$ctrlMain.append('<div class="voice-btn ctrl-btn-right">' +
            '<span title="音量调节" class="glyphicon glyphicon-volume-up" aria-hidden="true"></span>' +
            '<div id="' + this.id.slice(1, this.id.length) + 'volume"><input class="ctrl-btn-right volume" min="0" value="50" max="100" type="range" /></div>' +
            '</div>');
        this.$ctrlMain.append('<div class="rate-btn ctrl-btn-right">' +
            '<span title="倍速播放">倍速</span>' +
            '<ul id="' + this.id.slice(1, this.id.length) + 'playrate">' +
                '<li value="0.3">0.3</li>' +
                '<li value="0.5">0.5</li>' +
                '<li value="0.7">0.7</li>' +
                '<li value="1.0" class="active">1.0</li>' +
                '<li value="1.2">1.2</li>' +
                '<li value="1.5">1.5</li>' +
                '<li value="1.7">1.7</li>' +
                '<li value="2.0">2.0</li>' +
                '<li value="4.0">4.0</li>' +
                '<li value="16.0">16.0</li>' +
            '</ul>' +
            '</div>');
        //播放器状态
        this.video = $(this.id + " .danmu-video").get(0);
        this.current = 0;  //当前播放时间
        this.duration = this.video.duration;  //总时间
        this.danmuPlayerFullScreen = false;
        this.isLoop = false;
        this.isPlaying = false
        //等待层
        $(this.id + " .danmu-player-load").shCircleLoader({
            keyframes: "0%   {background:black}\
                       40%  {background:transparent}\
                       60%  {background:transparent}\
                       100% {background:black}"
        });
        // 判断播放器ctrl位置，注意ctrl是新添加的
        this.ctrlPosition = function(ctrlpos){
            if(ctrlpos == 1){
                $(this.id +" .danmu-player-ctrl").css({
                    "left":"-.5px",
                    "border-left":"1px solid #000",
                    "border-right":"1px solid #000",
                    "bottom":"-50px",
                    "background-color":"rgba(0,0,0,1)"
                });
            }else{
                $(this.id +" .danmu-player-ctrl").css({
                    "left":"0",
                    "bottom":"0",
                    "background": "-webkit-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,.2))",
                    "background": "-o-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,.2))",
                    "background": "-moz-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,.2))",
                    "background": "linear-gradient(rgba(0,0,0,0), rgba(0,0,0,.2))"
                });
            }
        }
        if(this.options.playerCtrlPosition == 1){
            that.ctrlPosition(1);
        }
        $(document).click(function(){
            $(that.id +"volume").hide();
            $(that.id +"playrate").hide();
        });

        //播放暂停
        this.playPause = function (e) {
            if (e.data.video.paused) {
                e.data.video.play();
                this.isPlaying = true
                $(e.data.that.id + " .play-btn span").removeClass("glyphicon-play").addClass("glyphicon-pause");
            }
            else {
                e.data.video.pause();
                this.isPlaying = false
                $(e.data.that.id + " .play-btn span").removeClass("glyphicon-pause").addClass("glyphicon-play");
            }
        };

        //主计时器
        var mainTimer = setInterval(function () {
            //缓冲条
            var bufTime=$(that.id + " .danmu-video").get(0).buffered.end($(that.id + " .danmu-video").get(0).buffered.length-1);

            var buffPrecent = (bufTime/that.duration) * 100;
            $(that.id + ".danmu-player .ctrl-progress .buffered ").css("width", buffPrecent + "%");
        }, 1000);


        // 播放中，鼠标1.5秒不动隐藏控制条
        var ctrltimer = null;
        window.lastMove = new Date().getTime();
        $(window).on('mousemove', function(e){
            window.lastMove = new Date().getTime();
        });
        function operate_ctrl() {
            var now = new Date().getTime();
            if(now - lastMove > 1500 && (that.options.playerCtrlPosition == 0 || that.danmuPlayerFullScreen)) {
                $(that.id + " .danmu-player-ctrl").css('visibility','hidden');
            }else{
                $(that.id + " .danmu-player-ctrl").css('visibility','visible');
            }
        }
        ctrltimer = window.setInterval(operate_ctrl, 1000);

        //播放事件
        $(this.id + " .play-btn").on("click", {video: this.video, that: that}, function (e) {
            that.playPause(e);
        });
        var screen_time = null;
        $(this.id + " .danmu-video").on("click", {video: this.video, that: that}, function (e) {
            clearTimeout(screen_time);
            screen_time = setTimeout(function(){
                that.playPause(e);
            }, 300);
        });
        // 空格键控制播放事件，左右键控制快进事件
        $(this.id).attr("tabindex",1);
        $(this.id).on('keyup', {video: this.video, that: that}, function (e) {
            if(e.keyCode == 32){
                that.playPause(e);
            }
        });
        $(this.id).on('keydown', {video: this.video, that: that}, function (e) {
            var aimTime;
            if(e.keyCode == 37){ // 后退
                if(e.data.video.currentTime > 5){
                    aimTime = e.data.video.currentTime - 5;
                }else{
                    aimTime = 0;
                }
            }else if(e.keyCode == 39){ // 快进
                if(e.data.video.duration - e.data.video.currentTime > 10){
                    aimTime = e.data.video.currentTime + 5;
                }else{
                    aimTime = e.data.video.duration - 1;
                }
            }
            if(e.keyCode == 37 || e.keyCode == 39){
                // 将时间写入显示出来
                var curMin = parseInt(aimTime / 60);
                var curSec = parseInt(aimTime % 60) < 10 ? "0" + parseInt(aimTime % 60) : parseInt(aimTime % 60);
                $(e.data.that.id + " .current-time").text(curMin + ":" + curSec);
                // 更新进度条
                var percentage = 100 * aimTime / e.data.that.duration;
                $(e.data.that.id + '.danmu-player .ctrl-progress .current ').css('width', percentage + '%');
                $(e.data.that.id + " .danmu-player-load").css("display","block");
                e.data.video.currentTime = aimTime;
            }
            e.preventDefault();
        });

        //waiting事件
        $(this.id + " .danmu-video").on('waiting', {that: that}, function (e) {
            $(e.data.that.id + " .danmu-player-load").css("display","block");
        });

        // 下一集事件
        $(this.id + " .next-btn").on("click", {that: that}, function (e) {
            $(that.options.nextButton).click();
        });
        // 倍速播放事件
        $(this.id +" .rate-btn").click(function(e){
            e.stopPropagation();
            if($(that.id +"playrate").is(":hidden")){
                $(that.id +"playrate").show();
            }else{
                $(that.id +"playrate").hide();
            }
        });
        $(this.id +"playrate").click(function(e){
            e.stopPropagation();
        });

        // 倍速切换
        $(this.id + "playrate li").on('click', {that: that}, function (e) {
            var play_rate = $(this).attr('value');
            $(this).siblings('li').removeClass('active');
            $(this).addClass('active');
            if(play_rate == '1.0'){
                $(that.id + " .rate-btn span").text('倍速');
            }else{
                $(that.id + " .rate-btn span").text(play_rate);
            }
            e.data.that.video.playbackRate = play_rate;
            $(that.id +"playrate").hide();
        });

        // 音量调节事件
        $(this.id +" .voice-btn").click(function(e){
            e.stopPropagation();
            if($(that.id +"volume").is(":hidden")){
                $(that.id +"volume").show();
            }else{
                $(that.id +"volume").hide();
            }
        });
        $(this.id +"volume").click(function(e){
            e.stopPropagation();
        });

        // 调节视频声音大小
        $(this.id + " .volume").on('mousemove touchmove', {that: that}, function (e) {
            e.data.that.video.volume = e.target.value / 100;
        });

        //进入全屏
        this.requestFullScreen = function() {
            var de = document.documentElement;
            if (de.requestFullscreen) {
                de.requestFullscreen();
            } else if (de.mozRequestFullScreen) {
                de.mozRequestFullScreen();
            } else if (de.webkitRequestFullScreen) {
                de.webkitRequestFullScreen();
            }
            that.ctrlPosition(0);
            $('body').css('overflow', 'hidden');
        }
        //退出全屏
        this.exitFullscreen = function() {
            var de = document;
            if (de.exitFullscreen) {
                de.exitFullscreen();
            } else if (de.mozCancelFullScreen) {
                de.mozCancelFullScreen();
            } else if (de.webkitCancelFullScreen) {
                de.webkitCancelFullScreen();
            }
            that.ctrlPosition(that.options.playerCtrlPosition);
            $('body').css('overflow', 'auto');
        }

        //全屏事件
        $(this.id + " .full-screen").on("click", {video: this.video, that: that}, function (e) {
            if (!e.data.that.danmuPlayerFullScreen) {
                // 进入全屏
                that.requestFullScreen();
                $(e.data.that.id).addClass("danmu-player-full-screen");
                e.data.that.danmuPlayerFullScreen = true;
                $(e.data.that.id + " .full-screen span").removeClass("glyphicon-resize-full").addClass("glyphicon-resize-small");
            }else{
                that.exitFullscreen();
                $(e.data.that.id).removeClass("danmu-player-full-screen");
                e.data.that.danmuPlayerFullScreen = false;
                $(e.data.that.id + " .full-screen span").removeClass("glyphicon-resize-small").addClass("glyphicon-resize-full");
            }
        });
        // 双击全屏
        $(this.id + " .danmu-video").on("dblclick", {video: this.video, that: that}, function (e) {
            clearTimeout(screen_time);
            if (!e.data.that.danmuPlayerFullScreen) {
                that.requestFullScreen();
                $(e.data.that.id).addClass("danmu-player-full-screen");
                e.data.that.danmuPlayerFullScreen = true;
                $(e.data.that.id + " .full-screen span").removeClass("glyphicon-resize-full").addClass("glyphicon-resize-small");
            }else{
                that.exitFullscreen();
                $(e.data.that.id).removeClass("danmu-player-full-screen");
                e.data.that.danmuPlayerFullScreen = false;
                $(e.data.that.id + " .full-screen span").removeClass("glyphicon-resize-small").addClass("glyphicon-resize-full");
            }
        });

        // 切换时增加变化
        $(this.id + " .danmu-video").on('loadstart', {video: this.video, that: that}, function (e) {
            $(e.data.that.id + " .danmu-video").attr('poster', options.startposter);
            setTimeout(function(){
                if($(e.data.that.id + " .danmu-video").attr('poster') == options.startposter)
                $(e.data.that.id + " .danmu-video").attr('poster', options.poster);
            }, 800);
        });

        //时间改变事件
        $(this.id + " .danmu-video").on('loadedmetadata', {video: this.video, that: that}, function (e) {
            e.data.that.duration = e.data.video.duration;
            var duraMin = parseInt(e.data.that.duration / 60);
            var duraSec = parseInt(e.data.that.duration % 60) < 10 ? "0" + parseInt(e.data.that.duration % 60) : parseInt(e.data.that.duration % 60);
            $(e.data.that.id + " .duration").text(duraMin + ":" + duraSec);
            $(e.data.that.id + " .danmu-video").on('timeupdate', {
                video: e.data.video,
                that: e.data.that
            }, function (e) {
                $(e.data.that.id + " .danmu-player-load").css("display","none");
                var current = e.data.that.current = e.data.video.currentTime;
                var curMin = parseInt(current / 60);
                var curSec = parseInt(current % 60) < 10 ? "0" + parseInt(current % 60) : parseInt(current % 60);
                $(e.data.that.id + " .current-time").text(curMin + ":" + curSec);
                var percentage = 100 * current / e.data.that.duration;
                $(e.data.that.id + '.danmu-player .ctrl-progress .current ').css('width', percentage + '%');
                e.data.that.reviseFlag = e.data.that.reviseFlag + 1;
                // 判断是否播放完了
                if(e.data.video.currentTime == e.data.video.duration){
                    $(e.data.that.id + " .play-btn span").removeClass("glyphicon-pause").addClass("glyphicon-play");
                }
            });
            $(e.data.that.id + " .danmu-video").attr('poster', options.readyposter);
            if(that.options.isAutoPlay){
                that.playPause(e);
            }
        });

        //进度条事件
        $(this.id + " .ctrl-progress-box").on('click', {video: this.video, that: that}, function (e) {
            var sumLen = $(e.data.that.id + " .ctrl-progress").width();
            var pos = e.pageX - $(e.data.that.id + " .ctrl-progress").offset().left;
            var percentage = pos / sumLen;
            $(e.data.that.id + '.danmu-player .ctrl-progress .current ').css('width', percentage * 100 + '%');
            var aimTime = parseFloat(percentage * e.data.that.duration);
            // 将时间写入显示出来
            var curMin = parseInt(aimTime / 60);
            var curSec = parseInt(aimTime % 60) < 10 ? "0" + parseInt(aimTime % 60) : parseInt(aimTime % 60);
            $(e.data.that.id + " .current-time").text(curMin + ":" + curSec);
            $(e.data.that.id + " .danmu-player-load").css("display","block");
            e.data.video.currentTime = aimTime;
        });
        var timeDrag = false;
        $(this.id + " .ctrl-progress-box").on('mousedown touchstart', function (e) {
            timeDrag = true;
        });
        $(document).on('mouseup', function (e) {
            if (timeDrag) timeDrag = false;
        });
        $(this.id + " .ctrl-progress-box").on('mousemove touchmove', {video: this.video, that: that}, function (e) {
            var sumLen = $(e.data.that.id + " .ctrl-progress").width();
            var pos = e.pageX - $(e.data.that.id + " .ctrl-progress").offset().left;
            var percentage = pos / sumLen;
            if (percentage > 1) percentage = 1;
            if (percentage < 0) percentage = 0;
            var aimTime = parseFloat(percentage * e.data.that.duration);
            // 将时间写入显示出来
            var curMin = parseInt(aimTime / 60);
            var curSec = parseInt(aimTime % 60) < 10 ? "0" + parseInt(aimTime % 60) : parseInt(aimTime % 60);
            // 鼠标移动，显示当前时间
            $(e.data.that.id + " .ctrl-progress-time").text(curMin + ":" + curSec).css(
                'left', (pos - 15) + 'px').show();
            // 如果拖拽则进行视频跳转
            if (timeDrag) {
                $(e.data.that.id + '.danmu-player .ctrl-progress .current ').css('width', percentage * 100 + '%');
                $(e.data.that.id + " .current-time").text(curMin + ":" + curSec);
                $(e.data.that.id + " .danmu-player-load").css("display","block");
                e.data.video.currentTime = aimTime;
            }
        });
        $(this.id + " .ctrl-progress-box").on('mouseout', {that: that}, function(e){
            $(e.data.that.id + " .ctrl-progress-time").hide();
        });

    };//danmuplayer构造函数


    ManPlayer.DEFAULTS = {
        left: 0,
        top: 0,
        height: 360,
        width: 640,
        playerCtrlPosition: 0,  // 播放器控制条位置
        isAutoPlay: 0,  // 是否自动播放
        poster: '',  // 视频海报
        startposter: '',  // 开始加载视频时的海报
        readyposter: '',  // 视频加载完成时的海报
        nextButton: '',  // 下一集跳转按钮
    };


    function Plugin(option, arg) {
        return this.each(function () {
            var $this = $(this);
            var options = $.extend({}, ManPlayer.DEFAULTS, typeof option == 'object' && option);
            var data = $this.data('ManPlayer');
            var action = typeof option == 'string' ? option : NaN;
            if (!data) $this.data('danmu', (data = new ManPlayer(this, options)));
            if (action)    data[action](arg);
        })
    }

    $.fn.ManPlayer = Plugin;
    $.fn.ManPlayer.Constructor = ManPlayer;


})(jQuery);
